package top.psjj.news.web;

import com.google.gson.Gson;
import top.psjj.news.po.TNews;
import top.psjj.news.service.NewsService;
import top.psjj.news.service.impl.NewsServiceImpl;
import top.psjj.news.utils.ServiceProxyFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 新闻详细 以及评论
 */
@WebServlet("/detail")
public class NewsDetailAction extends BasicServlet{
    private NewsService newsService = (NewsService) ServiceProxyFactory.getService(NewsServiceImpl.class);
    private String baseUrl = "/WEB-INF/jsp/front/news/";
    //配置新闻详细页面的访问路径
    public void detailUI(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //获得新闻id
        int id= Integer.parseInt(req.getParameter("id"));
        req.setAttribute("id",id);
        req.getRequestDispatcher(baseUrl+"newsShow.jsp").forward(req,resp);
    }
    //新闻详细方法
    public void newsDetail(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //设置响应数据格式
        resp.setContentType("application/json;charset=utf-8");
        //获得新闻id
        int id= Integer.parseInt(req.getParameter("id"));
        //获得新闻数据
        TNews news = newsService.queryById(id);
        //将数据转为json数据
        Gson gson = new Gson();
        String result = gson.toJson(news);
        //响应数据
        resp.getWriter().print(result);
    }
}
